package com.hmdp.handler;

import com.hmdp.dto.Result;
import com.hmdp.exception.LoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 专门处理 LoginException
     */
    @ExceptionHandler(LoginException.class)
    public Result handleLoginException(LoginException ex) {
        log.error("登录异常: {}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理数据库唯一键冲突异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException ex) {
        log.error("数据库唯一键冲突: {}", ex.getMessage());
        return Result.error("该手机号已注册，请直接登录");
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException ex) {
        log.error("业务异常: {}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理运行时异常（捕获其他未处理的异常）
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常: {}", ex.getMessage(), ex); // 记录完整堆栈

        // 检查是否有具体的 cause
        Throwable cause = ex.getCause();
        if (cause instanceof DuplicateKeyException) {
            return handleDuplicateKeyException((DuplicateKeyException) cause);
        }

        return Result.error("系统错误，请稍后重试");
    }

    /**
     * 处理其他未预期的异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleUnexpectedException(Exception ex) {
        log.error("系统异常: {}", ex.getMessage(), ex);
        return Result.error("系统内部错误，请稍后重试");
    }
}